package gui.Stu;

import info.SubscribeForm;
import info.User;
import sql.Connect;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Calendar;
import java.util.Date;
import tool.checkDate;

public class History {
    private SubscribeForm[] subs;
    private Object[][] obj;
    private Date start=new Date();
    private Date end=new Date();
    JPanel oldListBox = new JPanel();
    JPanel newListBox = new JPanel();

    checkDate cd = new checkDate();

    String[] columnNames = {"id","类型", "开始时间","结束时间","理由","状态","活动"};

    // 自定义渲染器
    static class ButtonRenderer extends JButton implements TableCellRenderer {
        public ButtonRenderer() {
            setOpaque(true);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            setText("删除");
            return this;
        }
    }

    // 自定义编辑器
    static class ButtonEditor extends DefaultCellEditor {
        private JButton button;
        private String label;

        public ButtonEditor(JTable table,JCheckBox checkBox,Connect conn,User user) {
            super(checkBox);
            button = new JButton();
            button.setOpaque(true);

            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int row = table.getSelectedRow();

                    if(row != -1){
                       // 结束编辑
                        String id = table.getValueAt(row,0).toString();
                        System.out.println("当前id："+id);
                        conn.deleteSubscribe(id,user);
                        fireEditingStopped();

                    }
                }
            });
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
        boolean isSelected, int row, int column) {
            label = "删除";
            button.setText(label);
            return button;
        }

        @Override
        public Object getCellEditorValue() {
            return label;
        }

        @Override
        public boolean stopCellEditing() {
            return super.stopCellEditing();
        }
    }
    private JScrollPane getSL (Connect conn,User user){
        if(subs==null){
            obj = null;
        }else {
            obj = new Object[subs.length][7];
            int index = 0;
            while (index < subs.length) {
                obj[index][0] = subs[index].getId();
                obj[index][1] = subs[index].getType();
                obj[index][2] = subs[index].getStartDate();
                obj[index][3] = subs[index].getEndDate();
                obj[index][4] = subs[index].getReason();
                obj[index][5] = subs[index].getMessage();
                obj[index][6] = "活动";
                index++;
            }
        }
            DefaultTableModel data = new DefaultTableModel(obj, columnNames);
            JTable dataTable = new JTable(data);
            //当设置了单元格的点击监听事件，则JTable不会使用原来的点击编辑单元格事件
            dataTable.getTableHeader().setReorderingAllowed(false);
            dataTable.getColumnModel().getColumn(6).setCellRenderer(new ButtonRenderer());
            dataTable.getColumnModel().getColumn(6).setCellEditor(new ButtonEditor(dataTable, new JCheckBox(),conn,user));
            dataTable.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {//仅当鼠标单击时响应
                    //得到选中的行列的索引值
                    int r = dataTable.getSelectedRow();
                    int c = dataTable.getSelectedColumn();
                    if (c == 6) {
                        // 阻止事件继续传播到 JTable 的 mouseClicked 事件处理
                        return;
                    }
                    //得到选中的单元格的值，表格中都是字符串
                    Object value = dataTable.getValueAt(r, c);
                    String info = r + "行" + c + "列值 : " + value.toString();
                    javax.swing.JOptionPane.showMessageDialog(null, info);
                }
            });
            JScrollPane SL = new JScrollPane(dataTable);
            SL.setSize(170, 200);
            return SL;

    }
    private JPanel refresh(Connect conn, User user,Date start,Date end) {
        if(start == null || end == null) {
            System.out.println("start"+start);
            System.out.println("end"+end);
            System.out.println("没有获取到时间");
            return null;
        }else {
            JPanel newListBox = new JPanel();
            subs = conn.getSubscribe(user, start, end);
            newListBox.add(getSL(conn,user));
            return newListBox;
        }
    }
    public JPanel createHistory(CardLayout cardLayout, JPanel mainPanel, Connect conn, User user){
        subs =  conn.getSubscribe(user);
        JPanel historyPage = new JPanel(new BorderLayout());

        JPanel topBox = new JPanel();
        // 使用日期作为搜索
        JPanel DataBox = new JPanel(new GridLayout(1,1));

        JPanel StartBox = new JPanel();
        SpinnerDateModel startModel = new SpinnerDateModel(new Date(), null, null, java.util.Calendar.MINUTE);
        JSpinner startSpinner = new JSpinner(startModel);
        JSpinner.DateEditor startEditor = new JSpinner.DateEditor(startSpinner, "yyyy-MM-dd");
        startSpinner.setEditor(startEditor);
        StartBox.add(startSpinner);

        // 创建结束日期时间选择器
        JPanel EndBox = new JPanel();
        SpinnerDateModel endModel = new SpinnerDateModel(new Date(), null, null, java.util.Calendar.MINUTE);
        JSpinner endSpinner = new JSpinner(endModel);
        JSpinner.DateEditor endEditor = new JSpinner.DateEditor(endSpinner, " yyyy-MM-dd");
        endSpinner.setEditor(endEditor);
        EndBox.add(endSpinner);
        DataBox.add(StartBox);
        DataBox.add(EndBox);
        //返回添加请假按钮
        JButton returnBtn = new JButton("返回");
        // 创建一个 JButton 作为搜索按钮
        JButton searchButton = new JButton("搜索");
        //请假数据列表框
        oldListBox.add(getSL(conn,user));

        historyPage.add(oldListBox,BorderLayout.CENTER);

        topBox.add(returnBtn);
        topBox.add(DataBox);
        topBox.add(searchButton);

        //返回按钮的点击事件处理
        returnBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
              cardLayout.show(mainPanel, "Subscribe");
            }
        });

        // 搜索按钮点击事件处理
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                historyPage.remove(oldListBox);
                newListBox = refresh(conn,user,start,end);
                historyPage.add(newListBox,BorderLayout.CENTER);
                oldListBox = newListBox;
                historyPage.revalidate();
                historyPage.repaint();
            }
        });
        //添加时间监听
        startSpinner.addChangeListener(e -> {
            Date startDate = (Date) startSpinner.getValue();
            Date endDate = (Date) endSpinner.getValue();
            //检查新输入的开始时间是否早于结束时间
            if( cd.checkStart(startDate,endDate)){
                start = startDate;
            }else{
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endDate);
                calendar.add(calendar.MONTH, -1);
                startSpinner.setValue(calendar.getTime());
                JOptionPane.showMessageDialog(null, "开始时间不得晚于结束时间", "错误", JOptionPane.ERROR_MESSAGE);
            }

        });

        endSpinner.addChangeListener(e -> {
            Date startDate = (Date) startSpinner.getValue();
            Date endDate = (Date) endSpinner.getValue();
            //检查新输入的结束时间是否晚于开始时间
            if (cd.checkEnd(endDate,startDate)){
                end = endDate;
            }else{
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(startDate);
                calendar.add(calendar.MONTH, 1);
                endSpinner.setValue(calendar.getTime());
                JOptionPane.showMessageDialog(null, "结束时间不得早于开始时间", "错误", JOptionPane.ERROR_MESSAGE);

            }

        });

        historyPage.add(topBox,BorderLayout.NORTH);

        return historyPage;
    }
}
